from rest_framework.views import APIView
from rest_framework.response import Response
from utils.pagination import MyPagination
from utils.base_response import BaseResponse
from django.http.request import QueryDict
import datetime


class GenericAPIView(APIView):  # 通用类
    query_set = None  # 接口表
    serializer_class = None  # 序列化类
    input_get_list = None  # 配置的get列表
    input_put_list = None  # 配置的put列表
    input_delete_list = None  # 配置的删除列表
    input_dict = None

    def get_queryset(self):  # 获取queryset
        return self.query_set

    def get_serializer(self, *args, **kwargs):  # 获取序列化类
        return self.serializer_class(*args, **kwargs)

    def get_input_get_list(self):  # 获取input_list
        return self.input_get_list

    def get_input_put_list(self):
        return self.input_put_list

    def get_input_delete_list(self):
        return self.input_delete_list

    def get_input_dict(self):  # 获取input_dict
        return self.input_dict()


class ListModelMixin(object):
    def list(self, request):  # 获取数据列表
        input_get_list = self.get_input_get_list()
        input_dict = self.get_input_dict().get_query_params(request, input_get_list)
        queryset = self.get_queryset().filter(**input_dict)
        page_obj = MyPagination()
        page_queryset = page_obj.paginate_queryset(queryset, request, view=self)
        ser_obj = self.get_serializer(page_queryset, many=True)
        return page_obj.get_paginated_response(ser_obj.data)


class CreateModelMixin(object):
    def create(self, request):
        res = BaseResponse()
        data = request.data
        if data:
            if isinstance(data, QueryDict):
                _mutable = data._mutable
                data._mutable = True
                data['create_time'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                data._mutable = _mutable
            else:
                data['create_time'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')

        serializer = self.get_serializer(data=data)
        if serializer.is_valid():
            serializer.save()
            res.data = serializer.data
            res.msg = '创建成功'
        else:
            res.msg = '添加失败'
            res.error = serializer.errors
            res.status = 1
        return Response(res.dict)


class UpdateModelMixin(object):  # 更新数据
    def update(self, request):
        res = BaseResponse()
        input_put_list = self.get_input_put_list()
        input_dict = self.get_input_dict().get_query_params(request, input_put_list)
        if not input_dict:
            res.status = 1
            res.msg = '更新失败，参数有误！'
            return Response(res.dict)
        queryset = self.get_queryset().filter(**input_dict)
        if queryset.count():
            data = request.data
            if data:
                if isinstance(data, QueryDict):
                    _mutable = data._mutable
                    data._mutable = True
                    data['update_time'] =datetime.datetime.now().strftime( '%Y-%m-%d %H:%M:%S' )
                    data._mutable = _mutable
                else:
                    data['update_time'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            serializer = self.get_serializer(queryset.first(), data=data, partial=True)
            if serializer.is_valid():
                serializer.save()
                res.data = serializer.data
                res.msg = '更新成功'
            else:
                res.msg = '数据异常，本次更新失败！'
                res.error = serializer.errors
                res.data = serializer.data
                res.status = 1
        else:
            res.msg = '没有对应数据,更新失败'
            res.status = 1
        return Response(res.dict)


class DeleteModelMixin(object):  # 删除数据
    def destroy(self, request):
        res = BaseResponse()
        input_delete_list = self.get_input_delete_list()
        input_dict = self.get_input_dict().get_query_params(request, input_delete_list)
        if not input_dict:
            res.status = 1
            res.msg = '删除失败，参数有误！'
            return Response(res.dict)
        queryset = self.get_queryset().filter(**input_dict)
        if queryset.count():
            try:
                queryset.delete()
                res.msg = '删除成功'
            except Exception as err:
                res.msg = '删除失败，请联系管理员'
                res.error = str(err.args)
                res.status = 1
        else:
            res.msg = '删除失败，没有对应数据'
            res.status = 1
        return Response(res.dict)


class CommonAPIView(GenericAPIView, ListModelMixin, CreateModelMixin, UpdateModelMixin, DeleteModelMixin):
    def get(self, request):
        return self.list(request)

    def post(self, request):
        return self.create(request)

    def put(self, request):
        return self.update(request)

    def delete(self, request):
        return self.destroy(request)
